package com.ljph.ljaker.controller;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.interceptor.Restful;
import com.ljph.jfinal.base.BaseController;
import com.ljph.jfinal.dto.ApiResult;
import com.ljph.kit.CommonKit;
import com.ljph.ljaker.enums.GoodType;
import com.ljph.ljaker.model.Good;
import com.ljph.ljaker.model.ext.ExtBrand;
import com.ljph.ljaker.model.ext.ExtGood;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 * Created by yuzhou on 16/9/23.
 */
@Before({Restful.class})
public class GoodController extends BaseController {

    private static final Logger _log = LoggerFactory.getLogger(GoodController.class);

    public void index() {
        ApiResult result = new ApiResult();
        List<Good> all = Good.dao.find("select * from " + CommonKit.getTableName(Good.class) + " order by updateTime desc");
        renderJson(result.setOk(true).setData(all).setTs());
    }

    public void save() {
        Integer extId = getParaToInt("extId");

        // 检查extId是否已经存在
        Good exist = Good.dao.findByExtId(extId);
        if(null != exist ){
            renderJson(new ApiResult(false, "商品" +  exist.getExt().getName() + "已经存在"));
            return;
        }

        Date now = new Date();
        Good good = new Good();
        good.setExtId(extId);
        good.setCreateTime(now);
        good.setUpdateTime(now.getTime());

        if(good.save()) {
            renderJson(new ApiResult(true, good));
        } else {
            renderJson(new ApiResult(false, "商品保存失败"));
        }
    }

    /**
     * 返回商品类别
     */
    @Clear({Restful.class})
    public void types() {
        _log.debug("Return good types in external good system");
        renderJson(new ApiResult(true, GoodType.toArray()));
    }

    /**
     * 返回商品类别下一级的品牌或者子类别
     */
    @Clear({Restful.class})
    public void brands() {
        Integer type = getParaToInt();
        renderJson(new ApiResult(true, ExtBrand.dao.findByType(type)));
    }

    /**
     * 返回商品子类别或者品牌下一级的所有商品
     */
    @Clear({Restful.class})
    public void goods () {
        Integer brandId = getParaToInt();
        renderJson(new ApiResult(true, ExtGood.dao.findByBrandId(brandId)));
    }
}
